/**
 * Created by CZ on 2017/4/6.
 */
module.exports = function ($scope,$rootScope,$localStorage,RequestService,commonConfig,$state,$filter) {
    $rootScope.fail = false; // 控制angular加载失败后显示的页面
    $rootScope.isShowFooter = false;
    //判断公共信息时候保存完毕
    $rootScope.commonMsgIsSave = false;
    //判断有无存储的数据，获取access_token
    if(!$localStorage.get('cloud')){
        getAccessToken();
    }else {
        console.log('已有LS数据');
        //判断保存时间有无过期
        var currentTime = new Date();
        //若过期则删除
        if(currentTime > $localStorage.get('cloud').deadline){
            console.log('保存时间过期');
            $localStorage.remove('cloud');
            getAccessToken();
        }else {
            console.log('保存时间没过期');
            //判断token是否失效
            RequestService.checkAccessToken($localStorage.get('cloud').token).then(function(response){
                // console.log(response);
                console.log('token有效');
                $rootScope.commonMsgIsSave = true;
                $rootScope.imgApi = commonConfig.$webroot+commonConfig.imgApi+'?access_token='+$localStorage.get('cloud').token+'&uuid=';
            },function(error){  //已存的token失效，重新获取
                // console.log(error);
                console.log('token已失效');
                $localStorage.remove('cloud');
                getAccessToken();
            });
        }
        //$rootScope.commonMsgIsSave = true;
    }
    function getAccessToken(){
        RequestService.getAccessToken().then(function(response){
            console.log(response);
            // 24*60*60*1000-1
            var deadline = new Date(new Date(new Date().toLocaleDateString().replace(/年|月|日/g,  "/")).getTime()+24*60*60*1000-1).getTime();
            $localStorage.set('cloud',{username:'',token:response.data.access_token,deadline:deadline});
            $rootScope.commonMsgIsSave = true; //避免用户退出清空用户数据导致获取token的延时使得别的端口不能识别token
            //全局定义所有图片初始路径
            $rootScope.imgApi = commonConfig.$webroot+commonConfig.imgApi+'?access_token='+$localStorage.get('cloud').token+'&uuid=';
        },function(error){
            console.log(error);
        });
    }

    //用户登录
    $rootScope.Login = function(){
        if($localStorage.get('cloud').username !== ''){
            $state.go('login');
        }else {
            var url = commonConfig.cloudHomepage+'login';
            //跳转到用户首页
            $localStorage.set('cloud-url',url); //保存跳转后的域名，以便验证code
            RequestService.getCode(encodeURIComponent(url));
            // RequestService.getCode('http://192.168.0.139:85/test.html');
        }
    };
};